<template>
  <!-- 修改新增弹窗 -->
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    :close-on-click-modal="issShow"
    :show-close="issShow"
    @closed="closeDialog"
  >
    <el-form ref="roleForm" :model="roleForm" :rules="roleRules">
      <el-form-item label="角色名称" prop="name" :label-width="formLabelWidth">
        <el-input v-model="roleForm.name" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="角色描述"
        :label-width="formLabelWidth"
        prop="description"
      >
        <el-input v-model="roleForm.description" autocomplete="off" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRole, updRoleById } from '@/api/role'
export default {
  name: 'DialogForm',
  data() {
    return {
      issShow: false,
      dialogFormVisible: false,
      // 表单信息
      roleForm: {
        name: '',
        description: ''
      },
      formLabelWidth: '120px',
      // 表单校验
      roleRules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {
    title() {
      return this.roleForm.id ? '修改角色' : '新增角色'
    }
  },
  methods: {
    // 关闭弹窗的回调事件
    closeDialog() {
      this.roleForm = {
        name: '',
        description: '',
        id: ''
      }
    },
    // 弹窗确定的点击事件
    confirm() {
      this.$refs.roleForm.validate(async valid => {
        if (valid) {
          if (this.roleForm.id) {
            await updRoleById({ id: this.roleForm.id }, this.roleForm)
            this.$message.success('修改成功')
          } else {
            await addRole(this.roleForm)
            this.$message.success('新增成功')
          }
          this.$parent.getRole()
          this.$refs.roleForm.resetFields()
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style></style>
